const http = require('http')
const querystring = require('querystring')
const fs = require('fs')


let user = {
    admin: '123456'
}
http.createServer((req, res)=>{
    let path,getData,postData
    if(req.method === 'GET'){
        console.log('登录来了')
        const url = new URL(`http://localhost:8080${req.url}`)
        path = url.pathname
        getData = url.searchParams//map类型
        complete()
    }else if(req.method === 'POST'){
        console.log('注册来了')
        path = req.url
        let result = []
        req.on('data', (buffer)=>{
            result.push(buffer)
        })
        req.on('end', ()=>{
           postData = querystring.parse(Buffer.concat(result).toString()) //字符串转成对象
        //    console.log(postData)
           complete()
        })
    }

    function complete(){
        if(path === '/login'){
            console.log(path)
            let username = getData.get('username')
            let password = getData.get('password')
            if(!user[username]){
                //页面显示
                res.writeHead(201, {
                    "Content-Type": "text/plain;charset=utf-8"
                })
                res.end(JSON.stringify({
                    err: 1,
                    msg: "用户名不存在"
                }))
            }else if(user[username] !== password){
                res.writeHead(202, {
                    "Content-Type": "text/plain;charset=utf-8"
                })
                res.end(JSON.stringify({
                    err: 1,
                    msg: "密码错误"
                }))
            }else{
                res.writeHead(200, {
                    "Content-Type": "text/plain;charset=utf-8"
                })
                res.end(
                    JSON.stringify({
                    err: 0,
                    msg: "登录成功!!!!!!!!!"
                })
                )
            }
        }else if(path === '/reg'){
            console.log(typeof postData)
            console.log(postData, postData.username)
            
            let { username, password } = postData
            if(user[username]){
                res.writeHead(201, {
                    "Content-Type": "text/plain;charset=utf-8"
                })
                res.end(JSON.stringify({
                    err: 1,
                    msg: "账户已经存在"
                }))
            }else{
                user[username] = password
                console.log(user)
                res.writeHead(200, {
                    "Content-Type": "text/plain;charset=utf-8"
                })
                res.end(JSON.stringify({
                    err: 0,
                    msg: "注册成功"
                }))
            }
        }else{
            fs.readFile(`./${path}`, (err, data)=>{
                if(err){
                    res.end('404')
                }else{
                    res.end(data)
                }
            })
        }
    }
}).listen(8080)